#pragma once

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <unordered_map>
#include "Comm.hpp"

using namespace std;

const std::string Sep = "\r\n";
const string LineSep = " ";
const string HeaderLineSep = ": ";
const std::string BlankLine = Sep;

bool ParseOneLine(string &str, string *out, const string &Sep)
{
    auto pos = str.find(Sep);
    if (pos == string::npos)
        return false;
    *out = str.substr(0, pos);
    str.erase(0, pos + Sep.size());

    return true;
}
//header:  key: value
bool SplitString(const string& header, const string& sep, string* key, string* value)
{
    auto pos = header.find(sep);
    if(pos == string::npos) return false;

    *key = header.substr(0, pos);
    *value = header.substr(pos+sep.size());

    return true;
}
// BS模式
class HttpRequest
{
    void ParseReqLine(string& _req_line,const string LineSep)
    {
        stringstream ss(_req_line);
        ss>>_method>>_uri>>_version;
    }
    bool ParseHeaderkv()
    {
        string key, value;
        for(auto& header: _req_header)
        {
            if(SplitString(header, HeaderLineSep, &key, &value))
            {
                _headerkv.insert(make_pair(key, value));
            }
        }
    }
    bool ParseHeader(string& request_str)
    {
        string line;
        while(1)
        {
            bool r = ParseOneLine(request_str, &line, Sep);
            if(r&&!line.empty())
            {
                _req_header.push_back(line);
            }
            else if(r && line.empty())
            {
                _blank_line = Sep;
                break;
            }
            else return false;

            ParseHeaderkv();
            return true;
        }
    }
public:
    HttpRequest()
    {
    }
    void Deserialize(string &request_str)
    {
        if (ParseOneLine(request_str, &_req_line, Sep)){
            // 提取请求行的详细字段
            ParseReqLine(_req_line, LineSep);
            ParseHeader(request_str);
            _body = request_str;
        } 
       
    }
    void Print()
    {
        std::cout <<"_method: "<<_method<<std::endl;
        std::cout <<"_uri: "<<_uri<<std::endl;
        std::cout <<"_version: "<<_version<<std::endl;

        for(auto& kv:_headerkv)
        {
            cout<<kv.first<<": "<<kv.second<<endl;
        }
        std::cout <<"_blank_line: "<<_blank_line<<std::endl;

        std::cout <<"_body: "<<_body<<std::endl;

    }
    ~HttpRequest()
    {
    }

private:
    string _req_line;
    vector<string> _req_header;
    string _blank_line;
    string _body;

    //反序列化过程中，细化我们解析出来的字段
    string _method;
    string _uri;
    string _version;
    unordered_map<string, string> _headerkv;
};

class HttpResponce
{
public:
    HttpResponce()
    {
    }
    ~HttpResponce()
    {
    }

private:
    string _resp_line;
    vector<string> _resp_header;
    string _blank_line;
    string _body;
};